package com.tql.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tql.mall.common.result.R;
import com.tql.mall.common.util.AuthContextHolder;
import com.tql.mall.model.comment.CommentInfo;
import com.tql.mall.model.comment.CommentInfoVo;
import com.tql.mall.service.CommentInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api(description = "评论信息接口")
@RestController
@RequestMapping("api/comment")
public class CommentInfoController {

    @Autowired
    private CommentInfoService commentInfoService;

    /**
     * 保存评论
     *
     * @return
     */
    @ApiOperation(value = "保存评论")
    @PostMapping("/auth/save")
    public R<Void> save(@RequestBody List<CommentInfoVo> commelist, HttpServletRequest req) {
        //获取用户的id
        String userId = AuthContextHolder.getUserId(req);
        if (StringUtils.isEmpty(userId)) {
            return R.fail();
        }
        Long customerId = Long.parseLong(userId);
        for (CommentInfoVo commentInfoVo : commelist) {
            commentInfoVo.setCustomerId(customerId);
            commentInfoService.addComment(commentInfoVo);
        }
        return R.ok();
    }

    /**
     * 获取某个 spuId 下的所有评论
     *
     * @return
     */
    @ApiOperation(value = "获取评论列表")
    @GetMapping("/{spuId}/{page}/{limit}")
    public R<List<CommentInfo>> getCommeList(@PathVariable Long spuId, @PathVariable Integer page, @PathVariable Integer limit) {
        Page<CommentInfo> page1 = new Page<>(page, limit);
        QueryWrapper<CommentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id", spuId);
        commentInfoService.page(page1, queryWrapper);
        return R.ok(page1.getRecords());
    }
}
